package com.app.controller.supermarket;

import com.app.dto.supermarket.MyCollectDto;
import com.app.mapper.supermarket.MyCollectRepository;
import com.app.mapper.supermarket.OddJobReleaseMapper;
import com.app.model.supermarket.CommentModel;
import com.app.model.supermarket.MktPersonModel;
import com.app.model.supermarket.OddJobPicListModel;
import com.app.model.supermarket.OddJobReleaseModel;
import com.app.service.supermarket.*;
import com.app.util.*;
import com.app.vo.supermarket.OddJobReleaseReturnVo;
import com.app.vo.supermarket.OddJobReleaseVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 零工类型 控制层
 *
 * @author Administrator
 */
@Controller
@RestController
public class OddJobReleaseController {

    @Autowired
    MktPersonService mktPersonService;
    @Autowired
    OddJobPicListService oddJobPicListService;
    @Autowired
    OddJobReleaseService oddJobReleaseService;

    @Autowired
    MyOddService myOddService;

    @Autowired
    MyCollectRepository myCollectRepository;
    @Autowired
    CommentService commentService;

    @Autowired
    OddJobReleaseMapper oddJobReleaseMapper;




    /**
     * 新增和修改零工
     *
     * @param oddType
     * @param oddName
     * @param startTime
     * @param endTime
     * @param number
     * @param oneWages
     * @param transaddress
     * @param workPresent
     * @param id
     * @param imgs
     * @param request
     * @return
     * @throws ParseException
     */
    @PostMapping("/groupOddWork")
    public Result<Object> groupOddWork(@RequestParam("oddType") String oddType,
                               @RequestParam("oddName") String oddName,
                               @RequestParam("startTime") String startTime,
                               @RequestParam("endTime") String endTime,
                               @RequestParam("number") Integer number,
                               @RequestParam("oneWages") String oneWages,
                               @RequestParam("transaddress") String transaddress,
                               @RequestParam("workPresent") String workPresent,
                               @RequestParam("id") Integer id,
                               @RequestParam("imgs") String imgs,
                               HttpServletRequest request
    ) throws ParseException {
        if (oddName == null || startTime == null || number == null || oneWages == null || transaddress == null) {
            throw new BizException(HttpStatus.NOT_FOUND, "不能为空!!!");
        }
        String token = request.getHeader("token");
        if(token==null)
        {
            return Result.error(405,"token不存在");
        }
        String mobile = TokenUtils.verify(token);
        MktPersonModel customer = mktPersonService.getModelByMobile(mobile);
        if(customer==null)
        {
            return Result.error(405,"用户不存在");
        }

        //上传图片
        OddJobPicListModel oddJobPiclist = new OddJobPicListModel();
        oddJobPiclist.setOid(id);
        oddJobPiclist.setImgUrl(imgs);

        if( imgs!=null&&imgs!=""){
        String str[]=imgs.split(",");
        for(int i=0;i<str.length;i++){
            OddJobPicListModel model = new OddJobPicListModel();
            model.setOid(customer.getId());
            model.setImgUrl(str[i]);
            oddJobPicListService.insert(model);
          }
        }
        OddJobReleaseModel model = new OddJobReleaseModel();
        model.setOddType(oddType);
        model.setOddName(oddName);
        model.setStartTime(startTime);
        model.setEndTime(endTime);
        model.setNumber(number);
        model.setMid(customer.getId());
        model.setOneWages(Double.valueOf(oneWages));
        model.setTransaddress(transaddress);
        model.setWorkPresent(workPresent);
        try {
            if (id > 0) {
                model.setId(id);
                model.setUpTime(CommonHelp.getNowTimestamp());
                oddJobReleaseService.update(model);
            } else {
                model.setCrtTime(CommonHelp.getNowTimestamp());
                model.setSurplusNumber(number);
                oddJobReleaseService.insert(model);
                String str[] = imgs.split(",");
                for (int i = 0; i < str.length; i++) {
                    OddJobPicListModel oicList = new OddJobPicListModel();
                    oicList.setOid(model.getId());
                    oicList.setImgUrl(str[i]);
                    oddJobPicListService.insert(oicList);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }

        return Result.success("操作成功");
    }

    @GetMapping("/updateState")
    public Result<Object> updateState(@RequestParam("id") int id,
                              @RequestParam("state") int state,
                              HttpServletRequest request) {
        String token = request.getHeader("token");
        if(token==null)
        {
            return Result.error(405,"token不存在");
        }
        String mobile = TokenUtils.verify(token);
        MktPersonModel customer = mktPersonService.getModelByMobile(mobile);
        if(customer==null)
        {
            return Result.error(405,"用户不存在");
        }
        try {
            OddJobReleaseModel model = oddJobReleaseService.getOddById(id,customer.getId());
            if (model != null) {
                model.setState(state);
                oddJobReleaseService.update(model);
            } else {
                return Result.error(500,"没有该零活或传参错误");
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.success("操作成功");
    }


    //删除
    @PostMapping("/delOddWork")
    public Result<Object> delWorkExp(@RequestParam("id") int id,HttpServletRequest request) {
        String token = request.getHeader("token");
        if(token==null)
        {
            return Result.error(405,"token不存在");
        }
        String mobile = TokenUtils.verify(token);
        MktPersonModel customer = mktPersonService.getModelByMobile(mobile);
        if(customer==null)
        {
            return Result.error(405,"用户不存在");
        }
        try {
            if (id > 0) {
                oddJobReleaseService.delete(id);
            } else {
              return Result.error(500,"请输入ID");
            }

        } catch (Exception e) {
            System.out.println(e);
        }

        return Result.success("操作成功");
    }

    //零工搜索模糊查询
    @GetMapping("/getOddWorkList")
    @ResponseBody
    public Result<Object> getOddWorkList(HttpServletRequest request) throws ParseException {
        String oddName = request.getParameter("oddName");
        String oddType = request.getParameter("oddType");
        int orderByType = Integer.parseInt(request.getParameter("orderByType"));
        JSONObject json = new JSONObject();
        OddJobReleaseModel model = new OddJobReleaseModel();
        model.setOddName(oddName);
        model.setOddType(oddType);
        model.setOrderByType(orderByType);
        List<OddJobReleaseModel> modelList = oddJobReleaseService.getOddJobReleaseListByModel(model);
        for (int i = 0; i < modelList.size(); i++) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Timestamp data1 = Timestamp.valueOf(modelList.get(i).getStartTime());//开始时间
            Timestamp data2 = Timestamp.valueOf(modelList.get(i).getEndTime());//结束时间
            String currentSimpleDateFormat3 = sdf.format(data1);
            String currentSimpleDateFormat4 = sdf.format(data2);
            modelList.get(i).setStartTime(currentSimpleDateFormat3);
             modelList.get(i).setEndTime(currentSimpleDateFormat4);
        }
        return Result.success(modelList);
    }

    /**
     * 我发的活
     *
     * @param request
     * @return
     * @throws ParseException
     */
    @GetMapping("/getOddWorkListByState")
    public Result<Object> getOddWorkListByState(HttpServletRequest request) throws ParseException {
        String state = request.getParameter("state");
        String token = request.getHeader("token");
        if(token==null)
        {
            return Result.error(405,"token不存在");
        }
        String mobile = TokenUtils.verify(token);
        MktPersonModel mktPerson = mktPersonService.getModelByMobile(mobile);
        if(mktPerson==null)
        {
            return Result.error(405,"用户不存在");
        }
        OddJobReleaseVo model = new OddJobReleaseVo();
        if (state != null && state != "") {
            model.setState(Integer.valueOf(state));
        }
        model.setMid(mktPerson.getId());
        List<OddJobReleaseVo> modelList = oddJobReleaseService.getOddJobReleaseListByState(model);
        for (int i = 0; i < modelList.size(); i++) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Timestamp data1 = Timestamp.valueOf(modelList.get(i).getStartTime());//开始时间
            Timestamp data2 = Timestamp.valueOf(modelList.get(i).getEndTime());//开始时间
            String startTime = sdf.format(data1);
            String endTime = sdf.format(data2);
            modelList.get(i).setStartTime(startTime);
            modelList.get(i).setEndTime(endTime);
        }
        if (modelList != null && modelList.size() > 0) {
            //查询招工中获取申请人数
            for (int i = 0; i < modelList.size(); i++) {

                if (modelList.get(i).getState() == 1) {
                    int count = myOddService.getCountByOidState(modelList.get(i).getId());
                    modelList.get(i).setEnrollment(count);
                }
                //1招工中2待结算3已完工4取消
                if (modelList.get(i).getState() == 1) {
                    modelList.get(i).setStateName("招工中");
                }
                if (modelList.get(i).getState() == 2) {
                    modelList.get(i).setStateName("待结算");
                }
                if (modelList.get(i).getState() == 3) {
                    modelList.get(i).setStateName("已完工");
                }
                if (modelList.get(i).getState() == 4) {
                    modelList.get(i).setStateName("已取消");
                }
            }

        }
        int countMid = oddJobReleaseService.countMid(mktPerson.getId());
        OddJobReleaseReturnVo vo = new OddJobReleaseReturnVo();
        vo.setList(modelList);
        vo.setCount(countMid);
        return Result.success(vo);
    }

    //根据ID查询零工详情
    @GetMapping("/getOddWork")
    public Result<Object> getWorkExp(HttpServletRequest request) throws ParseException {
        String id = request.getParameter("id");
        String token = request.getHeader("token");
        if(token==null)
        {
            return Result.error(405,"token不存在");
        }
        String mobile = TokenUtils.verify(token);
        MktPersonModel mktPerson = mktPersonService.getModelByMobile(mobile);
        if(mktPerson==null)
        {
            return Result.error(405,"用户不存在");
        }


        OddJobReleaseModel model = oddJobReleaseService.getOddJobReleaseById(Integer.valueOf(id));
        //格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Timestamp data = Timestamp.valueOf(model.getStartTime());
        Timestamp data2 = Timestamp.valueOf(model.getEndTime());
        String starTime = sdf.format(data);
        String endTime = sdf.format(data2);
        model.setStartTime(starTime);
        model.setEndTime(endTime);

        List<OddJobPicListModel> oddJobPiclist = oddJobPicListService.getListByOid(Integer.valueOf(id));
        model.setOddJobPiclist(oddJobPiclist);

        MktPersonModel Person = mktPersonService.getPersonByMid(model.getMid());
        //查询岁数

        Timestamp time = new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(Person.getBirthday() + "-01").getTime());
        String date = DateUtil.yearCompare(time, CommonHelp.getNowTimestamp());
        Person.setAge(date);
        //查手机号与加密手机号
        String starPhone = Person.getStarPhone().substring(0,3) +"****" + Person.getStarPhone().substring(7) ;
        Person.setStarPhone(starPhone);

        model.setPerson(Person);
        //查询收藏表（收藏对象接收）
        //判断对象是否为空
        //定义变量（判断是否收藏）
        QueryWrapper<MyCollectDto> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("key_id", id).eq("type", 1).eq("mid", mktPerson.getId());
        List<MyCollectDto> myCollects = myCollectRepository.selectList(queryWrapper1);
        if (myCollects.size() == 0) {
            model.setCollectState(1);
            //json.txt.put("status",1);
        } else {
            model.setCollectState(2);
            //json.txt.put("status",2);
        }
        //JSONObject jsonObject = new JSONObject();
        List<CommentModel> commentList = commentService.getCommentList(model.getMid());
        for (int i = 0; i < commentList.size(); i++) {
            SimpleDateFormat sdff = new SimpleDateFormat("yyyy-MM-dd HH:mm ");
            Timestamp data1 = Timestamp.valueOf(commentList.get(i).getCrtTime());
            String StrCrtTime = sdff.format(data1);
            commentList.get(i).setCrtTime(StrCrtTime);
        }
        model.setCommentList(commentList);
        int count = myOddService.getCountByOid(Integer.valueOf(id));
        JSONObject obj = new JSONObject(model);
        OddJobReleaseReturnVo vo = new OddJobReleaseReturnVo();
        vo.setCount(count);
        vo.setData(model);
        return Result.success(vo);
    }

//
//    @ApiOperation(value = "管理员获取待审核零工")
//    @RequestMapping(value = "/auditOddJob", method = RequestMethod.GET)
//    public String listOddJob(String startLonLat) {
//        QueryWrapper<OddJobReleaseVo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("state", 5);
//        List<OddJobReleaseVo> oddJobReleaseDto = oddJobReleaseMapper.selectList(queryWrapper);
//        for (int i = 0; i < oddJobReleaseDto.size(); i++) {
//            //根据零工id获取地址
//            String address = oddJobReleaseService.getAddressById(oddJobReleaseDto.get(i).getId());
//            //将地址转化为经纬度
//            Result endLonLat = gaoDeMapUtil.getLonLat(address);
//            String datas = (String) endLonLat.getDatas();
//            //根据两点之间的经纬度计算距离
//            Result distance1 = gaoDeMapUtil.getDistance(datas, startLonLat);
//            Long datas1 = (Long) distance1.getDatas();
//            //           oddJobReleaseDto.get(i).setJuli(datas1);
//        }
//        JSONObject json = new JSONObject();
//        json.put("data", oddJobReleaseDto);
//        json.put("code", "1");
//        json.put("msg", "成功");
//        return json.toString();
//    }

}
